package com.xy.cloud.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.xy.cloud.constant.HttpStatus;
import com.xy.cloud.properties.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * [Sa-Token 权限认证] 配置类
 *
 * @author kong
 */
@Configuration
@Slf4j
public class SaTokenConfigure {

    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    // 注册 Sa-Token全局过滤器
    @Bean
    public SaReactorFilter getSaReactorFilter() {

        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")
                // 开放地址
                .setExcludeList(ignoreWhite.getWhites())
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                  //  SaRouter.match("/**", r -> StpUtil.checkLogin());
                    SaRouter.match("/**", "/user/doLogin", r -> StpUtil.checkLogin());

                    SaRouter.match("/**",r -> StpUtil.checkPermission("user"));
                    SaRouter.match("/kafka/**",r -> StpUtil.checkPermission("user"));
                    SaRouter.notMatch("/xy-auth/wxUser/test").match("/xy-auth/wxUser/**", r -> StpUtil.checkPermission("user"));
                    // 权限认证 -- 不同模块, 校验不同权限
                    SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
                    SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
                    SaRouter.match("/goods/**", r -> StpUtil.checkPermission("goods"));
                    SaRouter.match("/orders/**", r -> StpUtil.checkPermission("orders"));
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    e.printStackTrace();
                    //这里详细判断，其实也没太必要
                    if (e instanceof NotLoginException) {
                        String type = ((NotLoginException) e).getType();
                        if (Objects.equals(type, "-1")) {
                            return new SaResult(HttpStatus.UNAUTHORIZED, e.getMessage(), null);
                        }
                        if (Objects.equals(type, "-2")) {
                            return new SaResult(HttpStatus.FORBIDDEN, e.getMessage(), null);
                        }
                    }
                    //权限报NotPermissionException异常
                    return SaResult.error(e.getMessage());
                });
    }
}
